<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./utils/reset.css" />
    <title>10三角形拼接方式绘制矩形</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script type="shader-source" id="vertexShader">
      precision mediump float;
      attribute vec2 triangle_Position;
      attribute vec2 canvas_Size;
      attribute vec4 triangle_Color;
      varying vec4 v_Color;

      void main(){
      	vec2 position = (triangle_Position / canvas_Size) * 2.0 - 1.0;
      	position = position * vec2(1.0, -1.0);
      	gl_Position = vec4(position, 0.0, 1.0);
      	v_Color = triangle_Color;

      }
    </script>
    <script type="shader-source" id="fragmentShader">
      precision mediump float;
      varying vec4 v_Color;

      void main(){
      	vec4 color = v_Color / vec4(255, 255, 255, 1);
      	gl_FragColor = color;
      }
    </script>

    <script src="./utils/webgl-helper.js"></script>

    <script>
      const canvas = getCanvas("#canvas");
      resizeCanvas(canvas);
      const gl = getContext(canvas);

      const program = createSimpleProgramFromScript(
        gl,
        "vertexShader",
        "fragmentShader"
      );
      gl.useProgram(program);

      let canvas_Size = gl.getAttribLocation(program, "canvas_Size");
      gl.vertexAttrib2f(canvas_Size, canvas.width, canvas.height);

      const triangle_Position = gl.getAttribLocation(
        program,
        "triangle_Position"
      );
      const triangle_Color = gl.getAttribLocation(program, "triangle_Color");

      const vertices = new Float32Array([
        30, 30, 255, 0, 0, 1, 30, 300, 255, 0, 0, 1, 300, 300, 255, 0, 0, 1, 30,
        30, 0, 255, 0, 1, 300, 300, 0, 255, 0, 1, 300, 30, 0, 255, 0, 1,
      ]);

      gl.enableVertexAttribArray(triangle_Position);
      gl.enableVertexAttribArray(triangle_Color);

      const vertexBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
      gl.vertexAttribPointer(triangle_Position, 2, gl.FLOAT, false, 24, 0);
      gl.vertexAttribPointer(triangle_Color, 4, gl.FLOAT, false, 24, 8);

      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(vertices),
        gl.STATIC_DRAW
      );

      gl.clearColor(0, 0, 0, 1);

      function render(gl) {
        gl.clear(gl.COLOR_BUFFER_BIT);
        if (vertices.length > 0) {
          gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 6);
        }
      }
      render(gl);
    </script>
  </body>
</html>
